<?php
// +----------------------------------------------------------------------
// | SparkShop 坚持做优秀的商城系统
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2099 http://sparkshop.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai  <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\service\UserService;

class User extends Base
{
    /**
     * 获取用户中心首页数据
     */
    public function index(UserService $userService)
    {
        return json($userService->getMyBaseInfo($this->user['id']));
    }

    /**
     * 获取用户基础数据
     */
    public function info(UserService $userService)
    {
        return json($userService->getUserInfo($this->user['id']));
    }

    /**
     * 修改用户信息
     */
    public function update(UserService $userService)
    {
        return json($userService->updateInfo(input('post.')));
    }

    /**
     * 修改绑定手机号
     */
    public function changePhone(UserService $userService)
    {
        $param = input('post.');
        $param['user_id'] = $this->user['id'];

        return json($userService->changePhone($param));
    }

    /**
     * 修改密码
     */
    public function changePassword(UserService $userService)
    {
        $param = input('post.');
        $param['user_id'] = $this->user['id'];

        return json($userService->changePassword($param));
    }
    /**
     * 获取用户OPENID
     */
    public function getOpenId(UserService $userService)
    {
        $code = input('code');
        if(!$code){
            $return =array('code'=>1,'msg'=>'缺少参数','data'=>[]);
            return json($return);
        }
        $appid = 'wx61c30a6d12c551fc';
        $appsecret = '094ce698039e32a37d72628509c99763';
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code ";
        //获取openid

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url );
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);;
        $output = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($output,true);
        if(isset($res['errcode'])){
            $return =array('code'=>1,'msg'=>'获取失败','data'=>[]);
            return json($return);
        }
        $return =array('code'=>0,'msg'=>'获取成功','data'=>$res);
        $this->app->db->name('user')->where('id',$this->user['id'])->update(['open_id'=>$res['openid']]);
        return json($return);
    }
}